<template>
  <div class="cart_container">
    <cart-header
      @share-show="getToggle"
      :goodsCount="list.length"
    ></cart-header>
    <my-count
      v-if="list.length > 0"
      :FullStatus="fullStatus"
      :totalPrice="totalPrice"
      :totalCount="totalCount"
      :cartIdList="cartIdList"
      :productIdList="productIdList"
      :istoggle="istoggle"
      @share-newFullStatus="getNewFullStatus"
      @del-good="deleteGoods"
    ></my-count>
    <ul class="main" v-if="list.length > 0">
      <li v-for="(item, i) in list" :key="i">
        <a>
          <cart-goods-item
            :productId="item.productId"
            :store_name="item.store_name"
            :suk="item.suk"
            :image="item.image"
            :price="item.price"
            :count="item.count"
            :status="item.status"
            :uniqueId="item.uniqueId"
            :cartId="item.cartId"
            @newStatus-click-change="getNewStatus"
          >
            <!-- @newStatus-input-change="getNewStatus" -->
            <cart-num
              :count="item.count"
              :ids="item.cartId"
              @share-newCount="getNewCount"
            ></cart-num>
          </cart-goods-item>
        </a>
      </li>
    </ul>

    <my-recommend v-if="list.length == 0"></my-recommend>
  </div>
</template>

<script>
import CartHeader from "@/views/cart/CartHeader.vue";
import MyCount from "@/views/cart/Count.vue";
import CartGoodsItem from "@/views/cart/CartGoodsItem.vue";
import CartNum from "@/views/cart/CartNum.vue";
import { mapState, mapMutations, mapGetters } from "vuex";
export default {
  name: "",
  data() {
    return {
      list: [],
      cartIdList: [],
      productIdList: [],
      // 记录切换模式
      istoggle: false,
    };
  },
  computed: {
    ...mapState("cart", ["cartList"]),
    ...mapGetters("cart", ["getCartData"]),
    ...mapState("cart", ["oldList"]),
    // 计算全选状态
    fullStatus() {
      return this.list.every((item) => item.status === true);
    },

    // 已经勾选的商品的总数量
    totalCount() {
      return this.list
        .filter((item) => {
          if (item.status) {
            return item;
          }
        })
        .reduce((totalCount, item) => {
          return (totalCount += item.count);
        }, 0);
    },
    // 计算已经被勾选商品的总价格
    totalPrice() {
      return this.list
        .filter((item) => {
          if (item.status) {
            return item;
          }
        })
        .reduce((totalPrice, item) => {
          return (totalPrice += item.count * item.price);
        }, 0);
    },
  },
  created() {
    this.initCartData();
    console.log("组件创建了")
  },
  methods: {
    ...mapMutations("cart", ["setCartListFn"]),
    ...mapMutations("cart", ["setGoodStatus"]),
    ...mapMutations("cart", ["setGoodAllStatus"]),
    ...mapMutations("cart", ["setGoodsCount"]),
    ...mapMutations("cart", ["setOldList"]),
    initCartData() {
      let token = localStorage.getItem("token");
      let url = "/api/cart/list";
      let pro = axios({
        method: "get",
        url: url,
        headers: {
          "Authori-zation": "Bearer " + token,
        },
      })
        .then((res) => {
          let list = [];
          let { status, data } = res.data;
          if (status == 200) {
            let { valid } = data;
            valid.forEach((item) => {
              let obj = {};
              // 产品Id
              obj.productId = item.product_id;
              // 具体产品Id 购物车产品Id
              obj.uniqueId = item.product_attr_unique;
              // 购物车Id 用于 支付
              obj.cartId = item.id;
              // 产品 store_name
              obj.store_name = item.productInfo.store_name;
              // 产品属性 suk
              obj.suk = item.productInfo.attrInfo.suk;
              // 产品图片
              obj.image = item.productInfo.attrInfo.image;
              // 产品价格
              obj.price = item.productInfo.attrInfo.price;
              // 数量
              obj.count = item.cart_num;
              // 是否被选中
              obj.status = false;
              //

              list.push(obj);
            });

            if(this.oldList.length == 0 || this.oldList == null){
             
              console.log("nnoe")
              console.log("get==>",this.oldList)
              this.list = list;
              this.setCartListFn(list);
              
              return
            }else if(this.oldList.length > 0){
                for(let i = 0 ; i < this.oldList.length ; i++){
                  for(let j = 0 ; j < list.length ; j++){
                    if(this.oldList[i].cartId == list[j].cartId){
                      
                      if(list[j].count != this.oldList[i].count){
                        this.oldList[i].count = list[j].count
                      }
                      list[j] = this.oldList[i]
                    }
                  }
                }

                list.some(item=>{
                  if(item.status == true){
                    this.cartIdList.push(item.cartId)
                    this.productIdList.push(item.productId)
                  }
                })

            }

            
            this.list = list;
            this.setCartListFn(list);
            console.log("成功==>", res.data);
          }
        })
        .catch((err) => {
          console.log("失败");
        });
    },

    initNewCountData(obj) {
      let token = localStorage.getItem("token");
      let url = "/api/cart/num";
      let pro = axios({
        method: "POST",
        url: url,
        data: {
          id: obj.id,
          number: obj.count,
        },
        headers: {
          "Authori-zation": "Bearer " + token,
        },
      })
        .then((res) => {
          let list = [];
          let { status, data } = res.data;
          if (status == 200) {
            console.log("修改数量成功", data);
          }
        })
        .catch((err) => {
          console.log("失败");
        });
    },

    // 点击支付

    // 接收子组件传过来的最新勾选状态
    getNewStatus(obj) {
      this.list.some((item) => {
        if (item.cartId == obj.id) {
          if (obj.status) {
            this.productIdList.push(item.productId);
            this.cartIdList.push(obj.id);
          } else {
            this.cartIdList.forEach((ele, i) => {
              if (ele == obj.id) {
                this.cartIdList.splice(i, 1);
              }
            });
            this.productIdList.forEach((ele, i) => {
              if (ele == item.productId) {
                this.productIdList.splice(i, 1);
              }
            });
          }

          item.status = obj.status;
          // this.setSelectFn(obj);
          this.setGoodStatus(obj);
          return;
        }
      });
    },

    // 接收子组件传过来的最新全选状态
    getNewFullStatus(val) {
      this.list.forEach((item) => {
        if (val) {
          this.cartIdList.push(item.cartId);
          this.productIdList.push(item.productId);
        } else {
          this.cartIdList = [];
          this.productIdList = [];
        }
        item.status = val;
        // setGoodAllStatus(val)
        // this.setSelectFn(this.list);
      });
      this.setGoodAllStatus(val);
    },

    // 接收子组件传过来的最新商品数量
    getNewCount(obj) {
      console.log("爸爸接收到了", obj);
      this.list.some((item) => {
        if (item.cartId == obj.id) {
          if (obj.count < 1) {
            item.count = 1;
          } else {
            item.count = obj.count;
          }

          return;
        }
      });
      this.initNewCountData(obj);
      this.setGoodsCount(obj);
    },

    // 接收子组件传过来的来的模块
    getToggle(val) {
      this.istoggle = val;
    },

    // 删除商品
    deleteGoods(arr) {
      console.log(arr);
      // 商品列表
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < this.list.length; j++) {
          if (arr[i] == this.list[j].cartId) {
            this.list.splice(j, 1);
            console.log("删除成功");
          }
        }
      }

      this.cartIdList = [];
    },
  },
  updated(){
    console.log("页面更新")
  },
  mounted(){
    
  },
  destroyed() {
    // this.setSelectFn(this.list)
    // this.setCartListFn(this.list)
    this.setOldList(this.list)
    localStorage.setItem('cartList', JSON.stringify(this.list))
    
    console.log("组件销毁了")
  },

  components: {
    CartHeader,
    MyCount,
    CartGoodsItem,
    CartNum,
  },
};
</script>

<style lang="scss" scoped>
.main {
  padding: 85px 0 100px;
  li {
    margin-bottom: 8px;
  }
}
/deep/.myRecommend {
  margin-top: 85px;
}
</style>


